package com.northwest_man.refactor_tool;


import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FindUntranslatable {
    // 作为参考的 strings.xml 文件
    private static final String rootStringFileAbsPath = "/Users/h/AndroidStudioProjects/patpat/Patpat/src/main/res/values/strings.xml";

    public static void main() {
        final StringBuilder fileContent = FileUtil.getFileContent(rootStringFileAbsPath);
        if (fileContent == null) {
            System.out.println("无法获取该文件内容" + rootStringFileAbsPath);
            return;
        }
        // <string[^>]+?translatable\s*=\s*"false"[^>]*?>
        final Pattern untranslatablePattern = Pattern.compile("<string[^>]+translatable\\s*=\\s*\"false\"[^>]*?>");
        final Matcher untranslatableMatcher = untranslatablePattern.matcher(fileContent);
        final List<String> untranslatableStringList = new ArrayList<>();
        while (untranslatableMatcher.find()) {
            // <string[^>]+?name\s*=\s*"([^"]+)"[^>]*?>
            final String label = untranslatableMatcher.group();
            final Pattern keyPattern = Pattern.compile("<string[^>]+?name\\s*=\\s*\"([^\"]+)\"[^>]*?>");
            final Matcher keyMatcher = keyPattern.matcher(label);
            if (keyMatcher.find()) {
                untranslatableStringList.add(keyMatcher.group(1));
            } else {
                throw new RuntimeException();
            }
        }
        final List<String> stringFileList = new ArrayList<>();
        FileUtil.recursionFolder(new File(Constants.copyParentResFolder), stringFileList, new Handler() {
            @Override
            public Object doHandle(File curFile, List allFileAbsolutePath) {
                if ("strings.xml".equals(curFile.getName())) {
                    allFileAbsolutePath.add(curFile.getAbsolutePath());
                }
                return null;
            }
        });
        for (final String fileAPath : stringFileList) {
            if (rootStringFileAbsPath.equals(fileAPath)) continue;
            final StringBuilder fromFileContent = FileUtil.getFileContent(fileAPath);
            if (fromFileContent == null) {
                System.out.println("无法获取源文件内容" + fileAPath);
                continue;
            }
            final Pattern keyPattern = Pattern.compile("<string[^>]+?name\\s*=\\s*\"([^\"]+)\"[^>]*?>[\\s\\S]+?</\\s*string\\s*>");

            final Matcher keyMatcher = keyPattern.matcher(fromFileContent);


            OutputStream tempOS = null;
            OutputStreamWriter writer = null;
            try {

                final List<String> shouldKeepStringList = new ArrayList<>();
                boolean foundExists = false;
                while (keyMatcher.find()) {
                    boolean found = false;
                    for (final String untranslatableKey : untranslatableStringList) {
                        if (untranslatableKey.equals(keyMatcher.group(1))) {
                            found = true;
                            break;
                        }
                    }
                    if (found) {
                        foundExists = true;
                    } else {
                        shouldKeepStringList.add(keyMatcher.group());
                    }
                }
                if (foundExists) {
                    // 写文件前创建目录和文件[开始]
                    final File pasteFile = new File(Constants.pastedParentResFolder + fileAPath.substring(Constants.copyParentResFolder.length()));
                    if (!pasteFile.getParentFile().exists()) {
                        if (!pasteFile.getParentFile().mkdirs()) {
                            throw new RuntimeException("副本文件夹创建失败");
                        }
                    }
                    final File[] files = pasteFile.getParentFile().listFiles();
                    if (files != null) {
                        for (File file : files) {
                            if (!file.delete()) {
                                throw new RuntimeException("无法删除副本文件夹中的文件: " + file.getName());
                            }
                        }
                    }
                    if (!pasteFile.exists()) {
                        try {
                            pasteFile.createNewFile();
                        } catch (IOException e) {

                            throw new RuntimeException("副本文件创建失败");
                        }
                    }
                    // 写文件前创建目录和文件[结束]
                    tempOS = new FileOutputStream(pasteFile);
                    writer = new OutputStreamWriter(tempOS);
                    writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n");
                    for (final String row : shouldKeepStringList) {
                        writer.write(row);
                        writer.write("\n");
                    }
                    writer.write("</resources>");
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (writer != null) writer.close();
                    if (tempOS != null) tempOS.close();
                } catch (Exception e) {
                    throw new RuntimeException("无法关闭写入流");
                }
            }
        }
    }

}
